package info.rflow.actions;

import info.rflow.Utils;
import info.rflow.model.RBlock;
import info.rflow.model.RFileParser;
import info.rflow.model.RWorkflowModel;
import info.rflow.util.RRunner;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;


/**
 * Document me!
 *
 * @author Holger Brandl
 */
public class ShowInExcelAction extends AbstractAction {

    private String outputName;
    private RBlock rBlock;


    public ShowInExcelAction(String outputName, RBlock rBlock) {
        this.outputName = outputName;
        this.rBlock = rBlock;

        putValue(NAME, "Open '" + outputName + "'");
        //        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.ALT_MASK));
    }


    public void actionPerformed(ActionEvent e) {
        try {
            String writeExcelScript = readFileAsString(this.getClass().getResourceAsStream("ShowInExcel.R"));
            File file = rBlock.prefixFileWithWD(outputName);
            if (file == null) {
                Utils.warnMissingWD();
                return;
            }

            writeExcelScript = writeExcelScript.replace("RDATA_FILE", file.getAbsolutePath());

            String cleanOutputName = outputName.replace(".RData", "");
            cleanOutputName = cleanOutputName.startsWith(".") ? cleanOutputName.substring(1, cleanOutputName.length()) : cleanOutputName;

            File tmpFile = File.createTempFile(cleanOutputName, ".csv");
            writeExcelScript = writeExcelScript.replace("TMP_FILE", tmpFile.getAbsolutePath());

            // convert the file into a temporary text file that can be opened with excel
            System.err.println(RRunner.evalRComand(writeExcelScript));

            if (tmpFile.isFile()) {
                Desktop.getDesktop().open(tmpFile);
            }


        } catch (IOException e1) {
            e1.printStackTrace();
        }


        //todo read the file --> check type --> create temporary file --> open in excel
    }


    public static String readFileAsString(InputStream is) {
        try {
            StringBuilder fileData = new StringBuilder(1000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                fileData.append(buf, 0, numRead);
            }
            reader.close();
            return fileData.toString();
        } catch (IOException e) {
            throw new RuntimeException("could not file from stream");
        }
    }


    public static void main(String[] args) {
        RWorkflowModel rWorkflowModel = RFileParser.readBlocks(new File("/Users/brandl/projects/rflow/testdata/simple.R"));

        RBlock firstBlock = rWorkflowModel.getBlocks().get(1);
        String outputName = firstBlock.getOutputs().get(0);
        new ShowInExcelAction(outputName, firstBlock).actionPerformed(null);
    }
}
